//
//  MyTaskStorageViewController.m
//  PlantGoWorker
//
//  Created by 纪翀 on 17/4/24.
//  Copyright © 2017年 m-training. All rights reserved.
//

#import "MyTaskStorageViewController.h"
#import "MyTaskStorageViewCell.h"
#import "MyTaskStorageDetailViewController.h"

@interface MyTaskStorageViewController ()
{
    NSArray *_dataArr;
    BMKLocationService *_locService;
    int  _checked;
}
@end

@implementation MyTaskStorageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initTabView];
    [self loadData];
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)loadData{
    NSString *token = [GlobalVar getVarName:@"token"];
    NSDictionary *postDic = @{
                              @"token":token,
                              @"stockroomId":_stockId,
                              @"workDate":_workDate,
                              };
    [SendRequestClass commonRequest:@"/api/mystoragetasks" postDic:postDic completionBlock:^(NSDictionary *succDic) {
        if ([[succDic objectForKey:@"code"] intValue] == SUCC_RESP)
        {
            NSLog(@"Success mystocktasks");
            NSDictionary *data = [succDic objectForKey:@"data"];
            _dataArr = [data objectForKey:@"works"];
            double finish = [[data objectForKey:@"finish"] doubleValue]/60;
            double unfinish = [[data objectForKey:@"unfinish"] doubleValue]/60;
            [_finishLabel setText:[NSString stringWithFormat:@"已完成%.2f小时", finish ]];
            [_unfinishLabel setText:[NSString stringWithFormat:@"未完成%.2f小时", unfinish ]];
            _checked = [[data objectForKey:@"checked"] intValue];
            
            
            
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            //设定时间格式,这里可以设置成自己需要的格式
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            //用[NSDate date]可以获取系统当前时间
            NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
            //输出格式为：2010-10-27 10:22:13
            
            
            [_tabView reloadData];
            
        }
        else{
            NSLog(@"Fail mystocktasks");
            [MyHint showHint:[succDic objectForKey:@"message"]];
        }
        
    } failureBlock:^(NSDictionary *failDic) {
        NSLog(@"Network error");
        [MyHint showHint:@"网络出现故障"];
    }];
}

- (IBAction)checkBtnClick:(id)sender {
    NSString *token = [GlobalVar getVarName:@"token"];
    BMKUserLocation *userLocation = [_locService userLocation];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //用[NSDate date]可以获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    //输出格式为：2010-10-27 10:22:13
    if (![currentDateStr isEqualToString:_workDate]){
        [MyHint showHint:@"日期不同不能签到"];
        return;
    }
    
    //日期不同或已签到，则不能点签到
    if (_checked){
        [MyHint showHint:@"已经签过到啦，不要再戳了~"];
        return;
    }
    
    
    NSDictionary *postDic = @{
                              @"token":token,
                              @"stockroomId":_stockId,
                              @"lat":[NSNumber numberWithDouble:userLocation.location.coordinate.latitude],
                              @"lng":[NSNumber numberWithDouble:userLocation.location.coordinate.longitude]
                              };
    [SendRequestClass commonRequest:@"/api/stockcheck" postDic:postDic completionBlock:^(NSDictionary *succDic) {
        if ([[succDic objectForKey:@"code"] intValue] == SUCC_RESP)
        {
            NSLog(@"Success storagecheck");
            _checked = YES;
            [MyHint showHint:@"签到成功"];
        }
        else{
            NSLog(@"Fail storagecheck");
            [MyHint showHint:[succDic objectForKey:@"message"]];
        }
        
    } failureBlock:^(NSDictionary *failDic) {
        NSLog(@"Network error");
        [MyHint showHint:@"网络出现故障"];
    }];

}



#pragma mark - UITabView
- (void)initTabView
{
    _tabView.rowHeight = 78;
    //    UIView * view = [[UIView alloc] initWithFrame:CGRectZero];
    //    [_tabView setTableHeaderView:view];
    _tabView.bounces = NO;
    [_tabView registerNib:[UINib nibWithNibName:@"MyTaskStorageViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_dataArr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *rowDic = [_dataArr objectAtIndex:indexPath.section];
    MyTaskStorageViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    [cell.titleLabel setText:[rowDic objectForKey:@"storageName"]];
    [cell.abstractLabel setText:[rowDic objectForKey:@"storageAddress"]];

    [cell.imgView sd_setImageWithURL:[NSURL URLWithString:[rowDic objectForKey:@"picUrl"]] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]];
    double unfinish = [[rowDic objectForKey:@"unFinishWorkTime"] doubleValue]/60;
    [cell.unfinishLabel setText:[NSString stringWithFormat:@"%.2f小时", unfinish ]];
    return cell;
}

- (UIView *)headerView
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectZero];
    return view;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (!_checked){
        [MyHint showHint:@"还未签到，请签到！"];
        return;
    }
    
    NSDictionary *rowDic = [_dataArr objectAtIndex:indexPath.section];
    MyTaskStorageDetailViewController *vc = [[MyTaskStorageDetailViewController alloc]init];
    vc.storageId = [rowDic objectForKey:@"storageId"];
    vc.workDate = _workDate;
    [self.navigationController pushViewController:vc animated:YES];
}


- (IBAction)backBtnClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


@end
